﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using LowLevelGraphics;
using LowLevelGraphics.Filter;

namespace LowLevelGraphics.Filter
{
    /// <summary>
    /// 
    /// </summary>
    public class FadeFX : BaseImageFilter, ITwoSourceFilter
    {
        /// <summary>
        /// 
        /// </summary>
        public FadeFX()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_fadeFX"></param>
        internal FadeFX(FadeFX _fadeFX)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            return new FadeFX(this);
        }

        /// <summary>
        /// <seealso cref=" http://cimg.cvs.sourceforge.net/cimg/CImg/examples/fade_images.cpp?view=markup"/>
        /// </summary>
        /// <param name="img1"></param>
        /// <param name="img2"></param>
        /// <returns></returns>
        public UnsafeBitmap Process(UnsafeBitmap img1, UnsafeBitmap img2)
        {
            double pmin = 40;
            double pmax = 60;
            double angle = 0;
            // Compute the faded image.
            double ca = Math.Cos(angle), sa = Math.Sin(angle);
            double alpha;

            UnsafeBitmap dest = new UnsafeBitmap(img1.Size);
            int nWidth = img1.Width;
            int nHeight = img1.Height;

            for (int y = 0; y < nHeight; y++)
            {
                for (int x = 0; x < nWidth; x++)
                {
                    for (int z = 0; z < 3; z++)
                    {

                        double X = ((double)x / img1.Width - 0.5) * ca + ((double)y / img1.Height - 0.5) * sa;
                        if (X + 0.5 < pmin) alpha = 0;
                        else
                        {
                            if (X + 0.5 > pmax) alpha = 1;
                            else
                                alpha = (X + 0.5 - pmin) / (pmax - pmin);
                            dest[x, y, z] = (byte)((1 - alpha) * img1[x, y, z] + alpha * img2[x, y, z]);
                        }
                    }
                }
            }
            return dest;
        }
    }
}
